import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
NProgress.configure({ showSpinner: false, easing: 'ease', speed: 1000 }); // NProgress Configuration

import { createRouter, createWebHashHistory } from 'vue-router';
import { RoutesDataItem } from "@/utils/routes";
import UserLayoutRoutes from '@/layouts/UserLayout/routes';
import UserLayout from '@/layouts/UserLayout/index.vue';
import InitLayoutRoutes from '@/layouts/InitLayout/routes';
import InitLayout from '@/layouts/InitLayout/index.vue';
import { getToken } from '@/utils/localToken'
import { useRouterStore } from "@/store/router";
import { useUserStore } from '@/store/user'



const routes : Array<RoutesDataItem> = [
	{
		title: 'index',
		path: '/',
		name: "/",
		redirect: '/home/workplace',
	},

	{
		title: 'async',
		path: '/async',
		name: "async",
		component: () => import('@/layouts/SecurityLayout.vue'),

	},
	{
		title: '用户登录注册页面',
		path: '/usr',
		name: 'usr',
		redirect: '/login',
		component: UserLayout,
		children: UserLayoutRoutes
	},


	{
		title: 'init-layout.menu.init',
		path: '/init',
		name: 'init',
		redirect: '/init/reset-password',
		component: InitLayout,
		children: InitLayoutRoutes
	},

	{
		name: '404',
		title: 'app.global.menu.notfound',
		path: '/:pathMatch(.*)*',
		component: () => import('@/views/404/index.vue'),
	}

]



const router = createRouter({
	scrollBehavior(/* to, from, savedPosition */) {
		return { top: 0 }
	},
	history: createWebHashHistory(import.meta.env.BASE_URL),
	routes: routes,
});

var load = 0
const whiteList = ['login', 'register', 'reset-password']
router.beforeEach(async (to, from, next) => {
	// start progress bar
	NProgress.start();
	// console.log('to',to)
	// console.log(router.getRoutes())
	const store = useRouterStore()
	store.$state.meta = to.meta
	var menu = store.asyncRouters
	if (whiteList.indexOf(to.name) == -1) {
		const token = await getToken();
		
		if (!token) {
			router.push({ name: 'login' })
			next()
		} else {
			if (load === 0) {
				if (menu.length == 0) {
					const userStore = useUserStore();
					userStore.info();
					await store.LoadRouter();
					menu = store.asyncRouters;
				}
				load++;
				await addRouter(menu)

				next({ path: to.path });
			} else {
				next();
			}
		}
	} else {
		next()
	}


});
const addRouter = async (asyncRouters) => {
	if (asyncRouters) {

		asyncRouters.forEach(asyncRouter => {
			router.addRoute("async", asyncRouter)
		})
	}

}

router.afterEach(() => {
	// finish progress bar
	NProgress.done();
});

export default router;